package com.work.demo.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import com.password4j.Hash;
import com.password4j.Password;

/**
 * @ClassName : ScryptUtil
 * @Description : scrypt工具类(密码防暴破)
 * @Author : LinYa
 * @Date: 2022/5/25  13:42
 */
public class ScryptUtil {

	/**
	 * 对密码加密后的内容值截取16个字节
	 */
	private static final int LEN = 16;

	/**
	 * 加密字符串
	 * @param data 要加密的内容
	 * @return 加密后的内容
	 */
	public static String scryptStr(String data){
		TimeInterval timer = DateUtil.timer();
		Hash hash = Password.hash(data).addSalt("23211").withSCrypt();
		System.out.println(timer.interval());
		String result = hash.getResult();
		return StrUtil.subSufByLength(result,LEN);
	}


	/**
	 * 将二进制转换成16进制
	 * @method parseByte2HexStr
	 * @param buf
	 * @return
	 * @throws
	 * @since v1.0
	 */
	public static String parseByte2HexStr(byte buf[]){
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < buf.length; i++){
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * @method parseHexStr2Byte
	 * @param hexStr
	 * @return
	 * @throws
	 * @since v1.0
	 */
	public static byte[] parseHexStr2Byte(String hexStr){
		if(hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length()/2];
		for (int i = 0;i< hexStr.length()/2; i++) {
			int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
			int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}
}
